$(function () {
    let layer = layui.layer
    let form = layui.form
    // 初始化富文本编辑器
    initEditor()
            
    // 1. 初始化图片裁剪器
    var $image = $('#image')

    // 2. 裁剪选项
    var options = {
        aspectRatio: 400 / 280,
        preview: '.img-preview'
    }
    //获取修改文章的原本信息并显示
    function initForm() {
        let id = location.href.split('=')[1]
console.log(id);
        axios({
            method: 'GET',
            url:'/my/article/'+id
        }).then(res => {
           
            if (res.data.status !== 0) {
                return layer.msg(res.data.message)
            }
            form.val('formEdit', res.data.data)
            setTimeout(function () {
                tinyMCE.activeEditor.setContent(res.data.data.content)
            }, 500)
            let baseURL = 'http://api-breakingnews-web.itheima.net'
            let url = baseURL + res.data.data.cover_img
            $image.cropper('destroy')
            .attr('src', url)
            .cropper(options)
       })
 }

    initArtCateList()
    //获取数据并渲染
    function initArtCateList() {
        axios({
            url: '/my/article/cates'
        }).then(res => {
            if (res.data.status !== 0) {
                return layer.msg(res.data.message)
            }$(function () {
                initArtCateList()
               
                //select下拉菜单初始化（文章类别）
                function initArtCateList() {
                    axios({
                        url: '/my/article/cates'
                    }).then(res => {
                        if (res.data.status !== 0) {
                            return layer.msg(res.data.message)
                        }
                        let arr = [' <option value="">请选择文章所属分类</option>']
                        res.data.data.forEach(ele => {
                            arr.push(
                                `
                                <option value="${ele.Id}">${ele.name}</option>
                                `
                            )
            
                        });
                        let str = arr.join('')
                        $('[name=cate_id]').empty().html(str)
                        //render()可以渲染layui中的select/checkbox/radio
                        //内置模块》表单》更新渲染
                        form.render()
                        initForm()
                    })
            
            
            
            
                }
            
                
            
                // 3. 初始化裁剪区域
                $image.cropper(options)
                $('#chooseImageBtn').on('click', function () {
                    $('#chooseImageInp').click()
            
                })
                //点击上传事件
                $('#chooseImageInp').on('change', function (e) {
                    let file = e.target.files[0]
                    console.log(file);
                    if (file === undefined) {
                        return layer.msg('文件内容不能为空')
                    }
                    let newImgURL = URL.createObjectURL(file)
                    $image.cropper('destroy')
                        .attr('src', newImgURL)
                        .cropper(options)
                })
            
            
            
                let state = ''
                //添加state属性
                $('#btn1').on('click', function () {
                    state = '已发布'
                })
                $('#btn2').on('click', function () {
                    state = '草稿'
                })
            
                //表单提交事件，获取表单内容
                $('#formPub').on('submit', function (e) {
                    e.preventDefault()
                    //获取form表单数据
                    let fd = new FormData(this)
                    //把state属性添加到获取表单数据的对象里
                    fd.append('state', state)
                    //获取预览区域的图片信息，为blob对象
                    $image
                        .cropper('getCroppedCanvas', { // 创建一个 Canvas 画布
                            width: 400,
                            height: 280
                        })
                        .toBlob(function (blob) {       // 将 Canvas 画布上的内容，转化为文件对象
                            // 得到文件对象后，添加到fromData对象里
                            fd.append('cover_img', blob)
                            console.log(...fd);//展开获取的数据
                            //因为生成图片是异步操作，所以axios也要写在生成图片成功后
                            axios({
                                method: 'POST',
                                url: '/my/article/edit',
                                data: fd
                            }).then(res => {
                                if (res.data.status !== 0) {
                                    return layer.msg(res.data.message)
                                }
            
                                layer.msg('恭喜您，修改文章成功！')
                                setTimeout(function () {
                                    //跳转到文章列表页面
                                    window.parent.document.querySelector('#art_list').click()
                                }, 1500)
            
                            })
                        });
            
            
            
                })
            
            
            
            
            })
            let arr = []
            res.data.data.forEach(ele => {
                arr.push(`
                    <tr>
                        <td>${ele.Id}</td>
                        <td>${ele.name}</td>
                        <td>${ele.alias}</td>
                        <td>
                        <button data-id='${ele.Id}' class="btnEdit layui-btn-xs layui-btn">修改</button>
                        <button  data-id='${ele.Id}' class="btnDel layui-btn-xs layui-btn-danger layui-btn">删除</button>
                        </td>
                    </tr>
      
                `)

            });
            $('tbody').empty().html(arr.join(''))






        })
    }
    //添加文章分类和弹出层
    //弹出层的索引 
    let indexAdd = 0
    $("#btnAdd").on('click', function () {
        indexAdd = layer.open({
            type: 1,
            area: ['500px', '260px'],
            title: '添加文章分类',
            content:
                `
                <form id='formAdd'   class="layui-form" action="">
                <div class="layui-form-item">
                  <label class="layui-form-label">分类名称</label>
                  <div class="layui-input-block">
                    <input type="text" name="name" required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item">
                  <label class="layui-form-label">分类别名</label>
                  <div class="layui-input-block">
                    <input type="text" name="alias" required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                      <button class="layui-btn" lay-submit lay-filter="formDemo">确认添加</button>
                      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                  </div>
                </form>
                  
                `
        });



    })
    //事件委托给添加文章弹出层添加提交事件
    $("body").on('submit', '#formAdd', function (e) {
        e.preventDefault()
        axios({
            method: 'POST',
            url: '/my/article/addcates',
            data: $(this).serialize()
        }).then(res => {
            if (res.data.status !== 0) {
                return layer.msg(res.data.message)
            }
            layer.msg('恭喜您添加文章分类成功')
            //重新渲染页面
            initArtCateList()
            //可有可无
            $('#formAdd')[0].reset()
            //关闭弹出层
            layer.close(indexAdd)
        })

    })
    //修改弹出层搭建
    let indexEdit = 0
    $("tbody").on('click', '.btnEdit', function () {
        indexEdit = layer.open({
            type: 1,
            area: ['500px', '260px'],
            title: '修改文章分类',
            //    添加一个隐藏域用来存放id值
            content:
                `
            <form lay-filter='formEdit' id='formEdit' class="layui-form" action="">
        
            <input type="hidden" name="Id">
            <div class="layui-form-item">
              <label class="layui-form-label">分类名称</label>
              <div class="layui-input-block">
                <input type="text" name="name" required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-form-item">
              <label class="layui-form-label">分类别名</label>
              <div class="layui-input-block">
                <input type="text" name="alias" required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                  <button  class="layui-btn" lay-submit lay-filter="formDemo">确认修改</button>
                 
                </div>
              </div>
            </form>
              
            `
        });
        let id = $(this).attr('data-id')
        // console.log(id);
        axios({
            method: 'GET',
            url: '/my/article/cates/' + id

        }).then(res => {
            if (res.data.status !== 0) {
                return layer.msg(res.data.message)
            }
            layui.form.val('formEdit', res.data.data)
        })

    })
    // 事件委托给修改文章弹出层添加提交事件  
    $("body").on('submit', '#formEdit', function (e) {
        e.preventDefault()
        axios({
            method: 'POST',
            url: '/my/article/updatecate',
            data: $(this).serialize()
        }).then(res => {
            if (res.data.status !== 0) {
                return layer.msg(res.data.message)
            }
            layer.msg('恭喜您修改文章分类成功')
            //重新渲染页面
            initArtCateList()
            //可有可无
            $('#formEdit')[0].reset()
            //关闭弹出层
            layer.close(indexEdit)
        })

    })
    //点击删除按钮，删除相应的行
    $("tbody").on('click', '.btnDel', function () { 
    let id = $(this).attr('data-id')
    // console.log(id);
    layer.confirm('确定要删除吗？', {icon: 3, title:'提示'}, function(index){

         axios({
        method: 'GET',
        //冒号必须省略，/不能省略
        url: '/my/article/deletecate/' + id
    }).then(res => {
        if (res.data.status !== 0) {
            return layer.msg(res.data.message)
        }
        layer.msg(res.data.message)
        initArtCateList()
    })
        layer.close(index);
      });   
   
        
    })
    






})